package com.jstyle.beatecg.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.jstyle.beatecg.R;
import com.jstyle.beatecg.app.MyApplication;
import com.jstyle.beatecg.base.BaseActivity;
import com.jstyle.beatecg.ble.BleService;
import com.jstyle.beatecg.fragment.EcgFragment;
import com.jstyle.beatecg.fragment.InfoFragment;
import com.jstyle.beatecg.fragment.SportFragment;
import com.jstyle.beatecg.fragment.UserFragment;
import com.jstyle.beatecg.model.BleData;
import com.jstyle.beatecg.model.MyBluetoothDevice;
import com.jstyle.beatecg.util.HomeListener;
import com.jstyle.beatecg.util.LanguageHelp;
import com.jstyle.beatecg.util.RxBus;
import com.jstyle.beatecg.util.ScreenUtils;
import com.jstyle.beatecg.util.SharePreferenceUtils;
import com.jstyle.beatecg.util.SystemStatusManager;
import com.jstyle.beatecg.view.MyAlertDialog;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 主显示界面
 */
public class MainActivity extends BaseActivity {

    private final static int FRAGMENT_SPORT = 0;
    private final static int FRAGMENT_INFO = 1;
    private final static int FRAGMENT_ECG = 2;
    private final static int FRAGMENT_USER = 3;


    SportFragment sportFragment;//运动
    EcgFragment ecgFragment;//心电
    InfoFragment infoFragment;//历史
    UserFragment userFragment;//设置


    @BindView(R.id.rb_ECG)
    RadioButton rbHomepage;
    @BindView(R.id.rb_INFO)
    RadioButton rbSleepPlan;
    @BindView(R.id.rb_user)
    RadioButton rbUser;
    @BindView(R.id.rg_main)
    RadioGroup rgMain;
    @BindView(R.id.ll_title)
    RelativeLayout ll_title;
    private static final String TAG = "MainActivity";
    private FragmentManager fragmentManager;

    MyAlertDialog alertDialog;
    private HomeListener mHomeListen = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        changeAppLanguage();
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        initView();
        checkPermissionRequest();
        FindAMapLocationClient();
        alertDialog=new MyAlertDialog(this);
        mHomeListen = new HomeListener(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        LanguageHelp.changeAppLanguage(this);
    }
    @Override
    protected void onResume( ) {
        super.onResume();
        mHomeListen.startListen();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mHomeListen.stopListen();
    }
    private void FindAMapLocationClient(){
        final  AMapLocationClient   mlocationClient=  new AMapLocationClient(this);
       final AMapLocationClientOption     mLocationOption = new AMapLocationClientOption();
        mLocationOption.setOnceLocation(false);
        // 设置为高精度定位模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        mLocationOption.setInterval(2000);
        //设置定位回调监听
        mlocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                if (aMapLocation.getErrorCode() == 0) {
                    MyApplication.aMapLocation = aMapLocation;
                    mlocationClient.stopLocation();
                }
            }
        });
        mlocationClient.startLocation();
    }
    @Override
    public boolean onKeyDown(final int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_BACK&& event.getRepeatCount() == 0&& event.getAction() != KeyEvent.ACTION_UP){
                    moveTaskToBack(true);//最小化
                    return true;
                } else if(keyCode == KeyEvent.KEYCODE_HOME) {
                    //由于Home键为系统键，此处不能捕获，需要重写onAttachedToWindow()
                    Log.e("sxx","home");
                    moveTaskToBack(true);//最小化
                    return true;
                }
        return super.onKeyDown(keyCode, event);
    }

    @SuppressLint("CheckResult")
    public void checkPermissionRequest() {
        RxPermissions rxPermission = new RxPermissions(this);
        rxPermission.requestEach(
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_CALENDAR,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.VIBRATE,
                Manifest.permission.CAMERA,
                Manifest.permission.RECORD_AUDIO
        ).subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限
                            Log.e("wyl", permission.name + " is granted.");
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时。还会提示请求权限的对话框
                            Log.e("wyl",permission.name + " is denied. More info should be provided.");
                        } else {
                            // 用户拒绝了该权限，而且选中『不再询问』
                            Log.e("wyl", permission.name + " is denied.");
                        }
                    }
                });
    }
    public void changeAppLanguage() {
        String sta = SharePreferenceUtils.getSpString(SharePreferenceUtils.KEY_Language);
        // 本地语言设置
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        Locale myLocale = new Locale(TextUtils.isEmpty(sta) ? language : sta);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
    }


    private Disposable subscription;

    private void initView() {
        subscription = RxBus.getInstance().toObservable(BleData.class).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<BleData>() {
            @Override
            public void accept(BleData bleData) throws Exception {
                String action = bleData.getAction();
                if ("finish".equals(action)) {
                    finish();
                }else if(action.equals(BleService.ACTION_GATT_CONNECTED)){
                    MyBluetoothDevice myBluetoothDevice=    SharePreferenceUtils.getUser(MyApplication.context,SharePreferenceUtils.KEY_ADDRESS);
                    if(!myBluetoothDevice.getIsbind()){
                        alertDialog.show();
                    }
                }else if (BleService.diss.equals(action)){
                    if(alertDialog.isShowing()){
                        alertDialog.dismiss();
                    }
                }
            }
        });
        showStatusBar();
        fragmentManager = getSupportFragmentManager();
        startTransaction(FRAGMENT_SPORT);
        rgMain.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                int fragmentId = 0;
                switch (checkedId) {
                    case R.id.rb_SPORT:
                        fragmentId = FRAGMENT_SPORT;
                        break;
                    case R.id.rb_ECG:
                        fragmentId = FRAGMENT_ECG;
                        break;
                    case R.id.rb_INFO:
                        fragmentId = FRAGMENT_INFO;
                        break;
                    case R.id.rb_user:
                        fragmentId = FRAGMENT_USER;
                        break;
                }
                startTransaction(fragmentId);
            }

        });
    }


    protected void startTransaction(int fragmentId) {

        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        hideFragment(fragmentTransaction);
        switch (fragmentId) {
            case FRAGMENT_ECG:
                if (ecgFragment == null) {
                    ecgFragment = new EcgFragment();
                    fragmentTransaction.add(R.id.main_framelayout, ecgFragment);
                } else {
                    fragmentTransaction.show(ecgFragment);
                }
                break;
            case FRAGMENT_SPORT:
                if (sportFragment == null) {
                    sportFragment = new SportFragment();
                    fragmentTransaction.add(R.id.main_framelayout, sportFragment);
                } else {
                    fragmentTransaction.show(sportFragment);
                }
                break;
            case FRAGMENT_INFO:
                if (infoFragment == null) {
                    infoFragment = new InfoFragment();
                    fragmentTransaction.add(R.id.main_framelayout, infoFragment);
                } else {
                    fragmentTransaction.show(infoFragment);
                }
                break;
            case FRAGMENT_USER:
                if (userFragment == null) {
                    userFragment = new UserFragment();
                    fragmentTransaction.add(R.id.main_framelayout, userFragment);
                } else {
                    fragmentTransaction.show(userFragment);
                }
                break;
        }

        fragmentTransaction.commit();
    }

    private void hideFragment(FragmentTransaction fragmentTransaction) {
        hideFragment(ecgFragment, fragmentTransaction);
        hideFragment(infoFragment, fragmentTransaction);
        hideFragment(sportFragment, fragmentTransaction);
        hideFragment(userFragment, fragmentTransaction);
    }

    private void hideFragment(Fragment fragment, FragmentTransaction transaction) {
        if (fragment != null) {
            transaction.hide(fragment);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unsubscribe();
    }

    private void unsubscribe() {
        if (subscription != null && !subscription.isDisposed()) {
            subscription.dispose();
        }
    }

    @Override
    protected void showStatusBar() {

    }


}
